package own.stu.jobgib.playown.io.fileRead;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class HandleMaxRepeatProblem_v0 {

    public static void main(String[] args) throws Exception {
        HandleMaxRepeatProblem_v0 v0 = new HandleMaxRepeatProblem_v0();
        v0.readData(Constant.FILE_NAME);
    }

    /**
     * 统计数量
     */
    protected static Map<String, AtomicInteger> countMap = new ConcurrentHashMap<>();

    /**
     * 按照 "," 分割数据，并写入到countMap里
     */

    public void readData(String fileName) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "utf-8"));
        String line;

        int count = 1;
        Stopwatch stopwatch = Stopwatch.createStarted();
        while ((line = reader.readLine()) != null) {
            if (count % 100 == 0) {
                log.info("读取100行,总耗时间: {}", stopwatch.toString());// System.gc();
                Constant.SplitData.splitLine(line, countMap);
            }
            count++;
        }
        stopwatch.stop();
        log.info("end: {}", stopwatch.toString());

        findMostAge();
    }

    protected static void findMostAge() {
        Integer targetValue = 0;
        String targetKey = null;
        Iterator<Map.Entry<String, AtomicInteger>> entrySetIterator = countMap.entrySet().iterator();
        while (entrySetIterator.hasNext()) {
            Map.Entry<String, AtomicInteger> entry = entrySetIterator.next();
            Integer value = entry.getValue().get();
            String key = entry.getKey();
            if (value > targetValue) {
                targetValue = value;
                targetKey = key;
            }
        }
        log.info("数量最多的年龄为: {} 数量为：{}", targetKey, targetValue);
    }
}
